package com.wangzhen.algorithm.Interview.ali;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Exchanger;
import java.util.concurrent.Semaphore;

/**
 * @description:  启5个线程，并发对1-10000之间的数字进行求和，并打印结果。（要求5个线程全部计算完再一次性汇总）
 * @datetime: 2021/3/30   下午7:49
 * @author: 王震
 */
public class ThreadSum {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(5);
        int []sums = new int[5];
        for (int i = 0; i < 5; i++) {
            int j = i;
            new Thread(()->{
               int start = j *2000+1;
               int end = (j+1)*2000;
               for (int a=start;a<=end;a++){
                   sums[j] = sums[j]+a;
               }
               latch.countDown();
            }).start();
        }
        latch.await();
        int sum = 0;
        for (int i = 0; i < sums.length; i++) {
            sum = sum+sums[i];
        }
        System.out.println(sum);

    }



}
